#include "common.h"

class Solution
{
public:
    int totalFruit(vector<int> &fruits)
    {
        int left = 0, right = 0;
        int sz = fruits.size();
        unordered_map<int, int> fruitkinds_nr;

        int max_length = 0;
        while (right < sz)
        {
            if (fruitkinds_nr.size() <= 2)
            {
                fruitkinds_nr[fruits[right]]++;
                right++;
            }
            else
            {
                --fruitkinds_nr[fruits[left]];
                if (fruitkinds_nr[fruits[left]] == 0)
                {
                    fruitkinds_nr.erase(fruits[left]);
                }
                left++;
            }

            if (fruitkinds_nr.size() <= 2)
            {
                max_length = max(max_length, right - left);
            }
        }
        return max_length;
    }
};



class Solution
{
public:
    int totalFruit(vector<int> &fruits)
    {
        int left = 0, right = 0;
        int sz = fruits.size();
        int hashes[(int)10e5 + 5];
        int kinds = 0;
        int ret = 0;
        memset(hashes, 0, sizeof(hashes));
        while(right < sz)
        {
            if(hashes[fruits[right]] == 0) kinds++;
            ++hashes[fruits[right++]];
            if(kinds > 2)
            {
                --hashes[fruits[left]];
                if(hashes[fruits[left]] == 0) kinds--;
                ++left;
            }
            ret = max(ret, right - left);
        }
        return ret;
    }
};